package com.ajieee.merge.runner.finance;

import cn.idev.excel.FastExcel;
import cn.idev.excel.context.AnalysisContext;
import cn.idev.excel.read.listener.ReadListener;
import com.ajieee.merge.entity.finance.po.EtfInfoPO;
import com.ajieee.merge.enums.finance.EtlType;
import com.ajieee.merge.enums.finance.Exchange;
import com.ajieee.merge.mapper.EtfInfoMapper;
import com.ajieee.merge.runner.finance.dto.EtfInfoExcelModel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClient;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 深交所ETF基本信息ETL
 *
 * @author ajieee
 * @date 2025-10-03
 */
@Slf4j
@Order(EtlOrder.INFO_ORDER)
@Component
@RequiredArgsConstructor
public class SzseEtfInfoEtl extends AbstractEtl {

	private final RestClient restClient;

	private final EtfInfoMapper etfInfoMapper;

	@Override
	public void doExecute() {
		String uri = UriComponentsBuilder.fromUriString("https://www.szse.cn/api/report/ShowReport")
				.queryParam("SHOWTYPE", "xlsx")
				.queryParam("CATALOGID", "1105")
				.queryParam("TABKEY", "tab1")
				.queryParam("selectJjlb", "ETF")
				.build().encode().toUriString();
		byte[] respBytes = restClient.get()
				.uri(uri)
				.retrieve()
				.body(byte[].class);
		Assert.notNull(respBytes, "深交所ETF及基本信息为空");

		List<EtfInfoPO> pos = new ArrayList<>();
		try (ByteArrayInputStream inputStream = new ByteArrayInputStream(respBytes)) {
			FastExcel.read(inputStream, EtfInfoExcelModel.class, new ReadListener<EtfInfoExcelModel>() {
				@Override
				public void invoke(EtfInfoExcelModel model, AnalysisContext analysisContext) {
					EtfInfoPO po = new EtfInfoPO();
					BeanUtils.copyProperties(model, po);
					po.setExchange(Exchange.SZSE);
					pos.add(po);
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext analysisContext) {
					etfInfoMapper.deleteByExchange(Exchange.SZSE);
					etfInfoMapper.insert(pos);
				}
			}).doReadAll();
		} catch (IOException e) {
			log.error("深交所ETF及基本信息读取异常", e);
		}

	}

	@Override
	public EtlType getType() {
		return EtlType.SZSE_ETF_INFO;
	}
}
